<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Greeting\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\Greeting\Contract\GreetingContract;
use MoChat\Plugin\Lottery\Contract\LotteryContract;
use MoChat\Plugin\Radar\Contract\RadarContract;

/**
 * 欢迎语-详情.
 *
 * Class Show.
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var LotteryContract
     */
    protected $lotteryService;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * @Inject
     * @var GreetingContract
     */
    private $greetingService;

    /**
     * @Inject
     * @var MediumContract
     */
    private $mediumService;

    /**
     * @RequestMapping(path="/workbench/greeting/show", methods="get")
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 获取当前登录用户
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['userId'] = (int) $user['logUserId'];
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $greetingId = $this->request->input('greetingId');
        // 获取欢迎语详情
        $greeting = $this->greetingService->getGreetingById((int) $greetingId);
        if (empty($greeting)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '此欢迎语不存在');
        }

        // 处理数据
        return [
            'greetingId' => $greeting['id'],
            'rangeType' => $greeting['rangeType'],
            'employees' => empty(Json::decode($greeting['employees'])) ? [] : $this->getEmployees(Json::decode($greeting['employees'])),
            'words' => $greeting['words'],
            'mediumId' => $greeting['mediumId'],
            'mediumContent' => empty($greeting['mediumId']) ? [] : $this->getMediumContent($greeting['mediumId']),
            'spanWelcomeStatus' => $greeting['spanWelcomeStatus'],
            'spanWelcome' => empty($greeting['spanWelcome']) ? [] : $this->getSpanWelcome(Json::decode($greeting['spanWelcome'])),
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'greetingId' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'greetingId.required' => '欢迎语ID 必填',
            'greetingId.integer' => '欢迎语ID 必需为整数',
            'greetingId.min  ' => '欢迎语ID 不可小于1',
        ];
    }

    /**
     * @param array $employeeIdArr 员工通讯录ID数组
     * @return array 响应数组
     */
    private function getEmployees(array $employeeIdArr): array
    {
        return $this->workEmployeeService->getWorkEmployeesById($employeeIdArr, ['id', 'name', 'avatar']);
    }

    /**
     * @param string $greetingId 欢迎语ID
     * @return array 响应数组
     */
    private function getMediumContent(string $greetingId): array
    {
        $mediumContent = [];
        if (is_numeric($greetingId)) {
            $medium = $this->mediumService->getMediumById((int) $greetingId, ['id', 'type', 'content']);
            $greet = empty($medium) ? [] : $this->mediumService->addFullPath(Json::decode($medium['content'], true), $medium['type']);
            $greet['type'] = 1;
            $greet['id'] = (int) $greetingId;
            $mediumContent[] = $greet;
        } else {
            $mediums = Json::decode($greetingId);
            foreach ($mediums as $mediumInfo) {
                if ((int) $mediumInfo['type'] === 1) {
                    $medium = $this->mediumService->getMediumById($mediumInfo['id'], ['id', 'type', 'content']);
                    $greet = empty($medium) ? [] : $this->mediumService->addFullPath(Json::decode($medium['content'], true), $medium['type']);
                    $greet['type'] = 1;
                    $greet['id'] = $mediumInfo['id'];
                    $mediumContent[] = $greet;
                } elseif ((int) $mediumInfo['type'] === 2) {
                    $lottery = $this->lotteryService->getLotteryById($mediumInfo['id'], ['id', 'name', 'description']);
                    $lottery['type'] = 2;
                    $mediumContent[] = $lottery;
                } elseif ((int) $mediumInfo['type'] === 3) {
                    $radar = $this->radarService->getRadarById($mediumInfo['id'], ['id', 'type', 'title', '', 'link', 'link_title', 'link_description', 'pdf_name', 'pdf', 'article', 'link_cover', 'description']);
                    $lottery['type'] = 2;
                    $mediumContent[] = $radar;
                }
            }
        }

        return $mediumContent;
    }

    private function getSpanWelcome(array $spanWelcome): array
    {
        foreach ($spanWelcome as &$item) {
            $item['mediumContent'] = $this->getMediumContent(Json::encode($item['mediumId']));
        }
        unset($item);
        return $spanWelcome;
    }
}
